package com.cyy.common.utils;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.generator.AbstractGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import lombok.Data;

import java.io.IOException;

public class CaptchaUtils {


    private final static String RANDOM_STR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    private final static String RANDOM_NUMBER = "0123456789";

    @Data
    public static class CodeEntity {
        public CodeEntity(String code, String img) {
            this.code = code;
            this.img = img;
        }

        //生成的验证码，存入缓存中，用于后续校验
        private String code;

        //生成的图片Base64编码,用于前端展示
        private String img;

    }


    public static CodeEntity generateCodeMath() throws IOException {
        RandomGenerator generator = new RandomGenerator(RANDOM_NUMBER, 6);
        return generateCode(generator);
    }


    public static CodeEntity generateCode() throws IOException {
        RandomGenerator generator = new RandomGenerator(RANDOM_STR, 4);
        return generateCode(generator);
    }

    public static CodeEntity generateCode(AbstractGenerator generator) throws IOException {
        AbstractCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100, generator, 60);
        captcha.setGenerator(generator);
        return new CodeEntity(captcha.getCode(), captcha.getImageBase64Data());
    }
}
